package basic_1015;

import java.util.Scanner;

public class Main2 {

	public static void main(String[] args) {
		
		Scanner scanner=new Scanner(System.in);
		
		String startAddress=scanner.next();
		int NodeNum=scanner.nextInt();
		int K=scanner.nextInt();
		
		Node head=null;
		Node[]nodes=new Node[NodeNum];
		
		for(int i=0;i<NodeNum;i++) {
			
			String address=scanner.next();
			int data=scanner.nextInt();
			String next=scanner.next();
			
			Node node=new Node(data, address, next);
			
			nodes[i]=node;
			
			if(address.equals(startAddress)) {
				head=node;
			}
			
			for(Node anode:nodes) {
				if(anode!=null) {
					if(anode.nextAddress.equals(address)) {
						anode.next=node;
					}else if(next.equals(anode.address)) {
						node.next=anode;
					}
				}
			}
		}

		int last=NodeNum;
		Node lastPardEnd=null;
		while(last>=K) {
			
			Node[] partNodes=new Node[K];
			Node nextPardStart;
			Node ptr=lastPardEnd==null?head:lastPardEnd.next;
			
			for(int i=0;i<K;i++) {
				partNodes[i]=ptr;
				ptr=ptr.next;
			}
			
			nextPardStart=partNodes[K-1].next;
			
			for(int i=K-1;i>0;i--) {
				partNodes[i].next=partNodes[i-1];
			}
			
			partNodes[0].next=nextPardStart;
			
			if(lastPardEnd!=null) {
				lastPardEnd.next=partNodes[K-1];
			}else {
				head=partNodes[K-1];
			}
			lastPardEnd=partNodes[0];
			last-=K;
		}
		scanner.close();
		
		Node optr=head;
		while(optr!=null) {
			String nextAdd=optr.next==null?"-1":optr.next.address;
			System.out.println(optr.address+" "+optr.data+" "+nextAdd);
			optr=optr.next;
		}
	}
	
	static class Node{
		int data;
		String address;
		String nextAddress;
		Node next=null;
		
		Node(int data,String address,String nextAddress){
			this.data=data;
			this.address=address;
			this.nextAddress=nextAddress;
		}
		
		Node(int data,String address,Node next){
			this.data=data;
			this.address=address;
			this.next=next;
		}
	}
}
